from mitmproxy import http
from mitmproxy.http import Response


def request(flow: http.HTTPFlow):
    print("请求url-->", flow.request.url)
    # print("请求host-->", flow.request.host)
    # print("请求path-->", flow.request.path)
    # print("请求query-->", flow.request.query)
    # print("请求cookies-->", flow.request.cookies)
    # print("请求headers-->", flow.request.headers)
    # print("请求method-->", flow.request.method)
    # print("请求content-->", flow.request.content)

    # 修改 url 的请求都为baidu
    # flow.request.url = "https://www.baidu.com"

    # 构造响应信息->返回
    if flow.request.url.__contains__("baidu.com"):
        flow.response = Response.make(
            200,
            b'hello world',
            {"Content-Type": "text/html"}, )


def response(flow: http.HTTPFlow):
    print(flow.request.url)

    print(flow.response.url)
    print(flow.response.status_code)
    print(flow.response.headers)
    print(flow.response.text)

    # 修改响应
    flow.response = Response.make(
        200,
        b'hello world',
        {"Content-Type": "text/html"}, )

    # 可以修改 cookie
    flow.response.cookies = {}

if __name__ == '__main__':
    print("mitmproxy -q -p 7890 -s hook.py")
